<?php
namespace Home\Controller;
use OT\DataDictionary;
/**
 * 前台首页控制器
 * 主要获取首页聚合数据
 */
class IndexController extends HomeController {

	//系统首页
    public function index(){
        $category = D('Category')->getTree();
        $lists    = D('Document')->lists(null);
        $this->assign('category',$category);//栏目
        $this->assign('lists',$lists);//列表
        $this->assign('page',D('Document')->page);//分页
        $this->display();
    }

    /**
     * 报名接口
     */
    public function bmapi(){
        if(empty($_REQUEST['username'])){
            exit(json_encode(array('code'=>false)));
        }
        $dao=M('hy');
        $data=$dao->create();
        $id=$dao->add($data);
        echo json_encode(array('code'=>$id));
        exit;
    }

    public function receive(){
        if($_REQUEST['msgid']){
            $dao=M('MobileMessage');
            $where=array();
            $where['msgid']=$_REQUEST['msgid'];
            $data=array();
            $data=$dao->field('id,msgid')->where($where)->find();
            $data['restatus']=$_REQUEST['status'];
            $data['retime']=time();
            $dao->save($data);
            //F('receive',$dao->getlastsql());
        }
    }
    
    public function recomment(){
        //用户回复短信
        if($_REQUEST['mobile']){
            $dao=M('MobileRemessage');
            $data=array();
            $data['mobile']=$_REQUEST['mobile'];
            $data['message']=$_REQUEST['msg'];
            $data['ctime']=time();
            $data['spcode']=$_REQUEST['spCode'];
            $data['str']=serialize($_REQUEST);
            $dao->add($data);
            //F('re',$_REQUEST);
        }
    }
    // public function mob(){
        // dump(send_mobile_message('18620928289','xxx同学你好,我们将于xxxx年xx月xx日（X周X）上午/下午/晚上 XX点至XX点在XXXXXXXX举办『互联网+ 沙龙活动』,共同探讨互联网领域的兴趣话题，欢迎您与您的同学共同参与，请及时回复到场人数（回复数字即可）'));
    // }
    
    public function register() {
        $uid  = $this->login();
        $_GET['setup']=empty($_GET['setup'])?1:$_GET['setup'];
        $bm_object = D('MemberRegister');
        $map=array();
        $map['uid']=$uid;
        $map['status']='1';
        $bm_info=$bm_object->where($map)->find();
        $user=M('UcenterMember');
        $info=$user->field('password',true)->where(array('id'=>$uid))->find();
        if($_GET['setup']=='1'||empty($_GET['setup'])){
            if($bm_info){
                $this->redirect('Index/register/setup/2');
            }
            if($info['mobile']){
                $this -> assign('mobile', $info['mobile']);
            }
            $meta['title']='完善用户资料';
        }
        if($_GET['setup']=='2'){
            $paid=M('Paid');
            $map=array();
            $map['uid']=$uid;
            $jd=array('','一','二','三','四','五','六','七');
            $paidinfo=$paid->where($map)->order('`stage` DESC')->select();
            $stage=1;
            if($paidinfo){
                foreach($paidinfo as $v){
                    if($v['paid']==1 && $v['stage']>=$stage){
                        $stage=$v['stage']+1;
                    }
                }
                if($stage>7){
                    $this->error('您的课程都已经学完了，谢谢。', U('Index/index'));
                }
            }
            $map['stage']=$stage;
            $map['paid']='0';
            $paidinfo=$paid->where($map)->find();
            if(empty($paidinfo)){
                $map['title']='大学加单阶段培训费第'. $jd[$stage] .'阶段';
                $map['voucher']='0';
                $map['citme']=time();
                $map['id']=$paid->add($map);
            }else{
                $map=$paidinfo;
            }
            $this->assign('paid',$map);
            self::rongpay($info,$bm_info,$map);
            $this->assign('bm',$bm_info);
            $this->assign('userinfo',$info);
            $meta['title']='报名缴费';
        }
        Cookie('__forward__', $_SERVER['REQUEST_URI']);
        $this -> assign('uid', $uid);
        $this -> assign('setup', $_GET['setup']);
        $this->assign("meta",$meta);
        $this -> display();
    }

    function rongpay($info=array(),$bm_info=array(),$pinfo=array()){
        $keycode=array();
        $keycode['MD5key'] = "xTnWpotYBWj9";           //MD5key值为您在新付支付注册后所得、需要您向业务人员获取LQ9iq6R9F5mg
        $keycode['Merno']= "00000000000204";          //商户ID为您在新付支付注册后所得00000000000004
        $keycode['Signtype']= "M";                    //加密方式 目前只为M代表-MD5
        $keycode['Prdordno']= "IIC_".date("YmdHis").'U'.$pinfo['id'];  //订单编号 
        $keycode['bizType']= "10";                            //商户业务类型为您在新付支付注册时候设定
        $keycode['Prdordnam']= $pinfo['title'];                    //商品名称    
        $keycode['Ordamt']= "50000";                                    //支付金额 [必填]【以分为单位】
        $keycode['Orddate']= date("Ymd");                     //下单日期 [必填]交易时间： 
        $keycode['TranType']= "20102";                    //交易类型 
        $keycode['Paytype']= "01";                            //支付方式
        $keycode['ThirdParty']= "LLP"; 
        $keycode['custnam']= $bm_info['realname'];                     //买家姓名  
        $keycode['custmob']= $bm_info['mobile'];           //买家手机号
        $keycode['custmail']= $info['email']?$info['email']:$bm_info['mobile'].'@iic.cn';    //买家邮箱 
        $keycode['custcardno']= $keycode['Prdordno'];           //买家身份证号
        $keycode['Return_url']= "http://www.iic.cn/".U('Index/rongru');   //同步通知url
        $keycode['Notify_url']= "http://www.iic.cn/".U('Index/rongnu');           //[必填]支付完成后，后台接收支付结果，可用来更新数据库值
        //设置参与MD5加签的字段
        //merNo&signType&Prdordno&Prdordnam&Ordamt&Orddate&tranType&paytype&notify_url&md5key
        $md5src= $keycode['Merno']."&".$keycode['Signtype']."&".$keycode['Prdordno']."&".$keycode['Prdordnam']."&"
            .$keycode['Ordamt']."&".$keycode['Orddate']."&".$keycode['TranType']
            ."&".$keycode['Paytype']."&".$keycode['Notify_url']."&".$keycode['MD5key'];
        $keycode['inMsg'] = strtoupper(md5($md5src));
        $this->assign($keycode);
    }
    
    /**
     * 华融支付同步通知url Return_url
     */
    public function rongru(){
        // $_POST=F('rongru');
        $MD5key= "xTnWpotYBWj9";
        if(empty($_POST["Merno"])){
            $this->error('您的课程都已经学完了，谢谢。', U('Index/index'));
        }
        $Merno          =     $_POST["Merno"];
        $Prdordno       =     $_POST["Prdordno"];
        $settleDate     =     $_POST["settleDate"];
        $ordStatus      =     $_POST["ordStatus"];
        $notifyTyp      =     $_POST["notifyTyp"];
        $payordno       =     $_POST['payOrdNo'];
        $Ordamt         =     $_POST['Ordamt'];
        $signType       =     $_POST['signType'];
        $signature      =     $_POST['signature'];
        $Paychannel     =     $_POST['Paychannel'];
        //Merno&Prdordno&settleDate&ordStatus&notifyTyp&payOrdNo&Ordamt&signType&md5key
        $src=$Merno."&".$Prdordno."&".$settleDate."&".$ordStatus."&".$notifyTyp."&".$payordno."&".$Ordamt."&".$signType."&".$MD5key;
        $md5sign=strtolower(md5($Merno."&".$Prdordno."&".$settleDate."&".$ordStatus."&".$notifyTyp."&".$payordno."&".$Ordamt."&".$signType."&".$MD5key));
        $meta_title="收款失败";
        $msg="";
        if($signature==$md5sign){
            if('1'==$ordStatus){
                //支付成功 但是不操作数据库
                $meta_title='支付成功';
            }
        }
        $meta['title']='报名缴费';
        $this->assign('meta',$meta);
        $this -> assign('setup',3);
        $this->display('register');
    }
    
    /**
     * 华融支付服务器同步通知url Notify_url
     */
    public function rongnu(){
        // $_POST=F('rongnu');
        $MD5key= "xTnWpotYBWj9";
        $Merno          =     $_POST["Merno"];
        $Prdordno       =     $_POST["Prdordno"];
        $settleDate     =     $_POST["settleDate"];     
        $ordStatus      =     $_POST["ordStatus"];
        $notifyTyp      =     $_POST["notifyTyp"];
        $payordno       =     $_POST['payOrdNo'];
        $Ordamt         =     $_POST['Ordamt'];
        $signType       =     $_POST['signType'];       
        $signature      =     $_POST['signature'];
        $Paychannel     =     $_POST['Paychannel'];
        //Merno&Prdordno&settleDate&ordStatus&notifyTyp&payOrdNo&Ordamt&signType&md5key
        $src=$Merno."&".$Prdordno."&".$settleDate."&".$ordStatus."&".$notifyTyp."&".$payordno."&".$Ordamt."&".$signType."&".$MD5key;
        $md5sign=strtolower(md5($Merno."&".$Prdordno."&".$settleDate."&".$ordStatus."&".$notifyTyp."&".$payordno."&".$Ordamt."&".$signType."&".$MD5key));
        $map=array('orderno'=>$Prdordno);
        $_POST['md5key']=$MD5key;
        $update=array('payordno'=>$payordno,'ustr'=>serialize($_POST),'utime'=>time(),'upip'=>get_client_ip(),'status'=>$ordStatus);
        M('Paylogs')->where($map)->save($update);
        if ($signature == $md5sign) {
            if('1'==$ordStatus){
                //支付成功
                $paid_id=explode('U', $Prdordno);
                $paid_id=$paid_id['1'];
                if(500000==(int)$Ordamt && (int)$paid_id>0){
                    $data=array('id'=>$paid_id,'voucher'=>$payordno);
                    M('Paid')->save($data);
                    $md5=md5($Merno.'&'.$Prdordno.'&1&&MD5');
                    $dom = new \DOMDocument('1.0','utf-8');
                    $data = $dom->createElement('merchantRes');
                    $data->setAttribute('Merno',$Merno);
                    $data->setAttribute('Prdordno',$Prdordno);
                    $data->setAttribute('status','1');
                    $data->setAttribute('cause','');
                    $data->setAttribute('signType','MD5');
                    $data->setAttribute('signature',$md5);
                    $dom->appendChild($data);
                    header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
                    header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
                    header("Cache-Control: no-cache");
                    header("Pragma: no-cache");
                    header("Content-type: text/xml; charset=utf-8");
                    echo $dom->saveXML();
                    exit();
                }else{
                    exit();
                }
            }
        }else{
            //验证失败
            exit();
        }
    }
    
    public function baoming() {
        $_POST['uid'] = $this->login();
        if (IS_POST) {
            if (!I('post.realname')) {
                $this -> error('姓名不能为空！');
            }
            if (!I('post.mobile')) {
                $this -> error('电话不能为空！');
            }
            $idcard_no=(string)I('post.idcard_no');
            if (empty($idcard_no)) {
                $this -> error('身份证不能为空！');
            }
            $iso=(string) iso7064(substr($idcard_no, 0,17).'?');
            if($iso!=$idcard_no){
                $this -> error('身份证号码错误，请检查输入！');
            }
            $_POST['sex']=substr($idcard_no,16,1)%2==1?'1':'-1';
            $_POST['birthday']=substr($idcard_no, 6,8);
            $bm_object = D('MemberRegister');
            $_POST['ctime'] = $_POST['utime'] = time();
            $_POST['status'] = 1;
            $data = $bm_object -> create();
            if ($data) {
                $bm_object -> add();
                $this -> success('感谢你提交意向，我们的客服人员会尽快与您联系，谢谢。');
            } else {
                $this -> error($bm_object -> getError());
            }
        }
    }

    /**
     * 支付日志信息
     */
    public function paid(){
        $_POST['uid'] =is_login();
        if (IS_POST && $_POST['uid']) {
            $logs=M('Paylogs');
            $data=$logs->create();
            $data['status']=0;
            $data['ip']=get_client_ip();
            $data['ctime']=time();
            $logs->add($data);
            $array=array();
            $array['statusCode']=200;
            $array['message']='请完成支付,后查看订单状态';
            $array['forwardUrl']=U('User/paid');
            exit(json_encode($array));
        }else{
            $array=array();
            $array['statusCode']=300;
            $array['message']='登陆超时，请登录后完成支付。';
            $array['forwardUrl']=U('User/login');
            exit(json_encode($array));
        }
    }

}
